%%% File    : exchanger.erl
%%% Author  :  <>
%%% Description : 
%%% Created : 26 Mar 2011 by  <>

-module(exchanger).

-behaviour(gen_server).

-export([start/1]).
-export([init/1, handle_call/3, handle_cast/2, handle_info/2,
	terminate/2, code_change/3]).

-record(state, {sup}).

%%----
start(Sup) ->
    gen_server:start({local, ?MODULE}, ?MODULE, [Sup], []).

%%------
init([Sup]) ->
    process_flag(trap_exit, true),
    {ok, #state{sup=Sup}}.

handle_call({deliver, Msg}, _From, S) ->
    Res = router:router(Msg),
    {reply, Res, S};

handle_call(_Req, _From, S) ->
    {reply, ok, S}.

handle_cast({do_stop, Pid}, S=#state{sup=Sup}) ->
    case Pid =:= Sup of
	true ->
	    {stop, normal, S};
	false ->
	    {noreply, S} 
    end;
handle_cast(redirect, S) ->
    redirect(S);
handle_cast(_Msg, S) ->
    {noreply, S}.

handle_info({'EXIT', _, normal}, S) ->
    {noreply, S};
handle_info({'EXIT', Pid, shutdown}, S=#state{sup=Sup}) ->
    case Pid =:= Sup of
	true ->
	    exit(normal);
	false ->
	    {noreply, S}
    end;
handle_info({'EXIT', Pid, _}, S=#state{sup=Sup}) ->
    case Pid =:= Sup of
	true ->
	    redirect(S);
	false ->
	    {noreply, S}
    end;
handle_info(_Info, S) ->
    {noreply, S}.

terminate(_Reason, _S) -> 
    ok.

code_change(_Oldvsn, S, _Extra) ->
    {ok, S}.

%%--------
redirect(S) ->
    case global:whereis_name(exchanger_sup) of
	Pid when is_pid(Pid) ->
	    link(Pid),
	    gen_server:cast(Pid, {redirect, node(), self()}),
	    {noreply, S#state{sup=Pid}};
	undefined ->
	    gen_server:cast(self(), redirect),
            {noreply, S}
    end.
   
